﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Collections;
using System.Data.SqlClient;


namespace 网络编程
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static SQL_Connection conn = new SQL_Connection("Data Source=.;Initial Catalog=Book;Integrated Security=True");
        DataSet ds = Form1.conn.sql_search_database("select * from andr");
        Dictionary<string,Socket> dicScoket=new Dictionary<string,Socket>();
        List<string> liststr = new List<string>();
        private void btStart_Click(object sender, EventArgs e)
        {
            try
            {
                Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Any;
                IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(tb2.Text));
                serverSocket.Bind(port);
                ShowMsg("监听成功");
                serverSocket.Listen(10);
                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(serverSocket);
            }
            catch { }
        }
        private void ShowMsg(string str) 
        {
            tbx1.AppendText(str+"\r\n");
        }
        Socket socket;
        private void Listen(Object o) 
        {
            Socket serverSocket=o as Socket;
            while(true)
            {
                socket = serverSocket.Accept();
                dicScoket.Add(socket.RemoteEndPoint.ToString(), socket);
                cbx1.Items.Add(socket.RemoteEndPoint.ToString());
                ShowMsg(socket.RemoteEndPoint.ToString() + ":" + "已连接");
                cbx1.Text = socket.RemoteEndPoint.ToString();
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start(socket);
              
            }
        }
        private void Receive(Object o) 
        {
            Socket socket = o as Socket;
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int r = socket.Receive(buffer);
                    if (r == 0) { break; }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    string str1 = str.Substring(0, 2);
                    //str1s
                    if (str1 == "01") 
                    {
                        try
                        {
                            if (cbx1.SelectedItem == null)
                            {
                                MessageBox.Show("请选中要发送的客户端哟");
                            }
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                string str4 = ds.Tables[0].Rows[i][1].ToString();
                                string str5 = ds.Tables[0].Rows[i][2].ToString();
                                /*StringBuilder sb = new StringBuilder("");
                                sb.Append(str4);
                                sb.Append("/");
                                sb.Append(str5);*/
                                byte[] buffer1 = Encoding.UTF8.GetBytes(str4);
                                List<byte> list = new List<byte>();
                                list.Add(0);
                                list.AddRange(buffer1);
                                byte[] newBuffer = list.ToArray();
                                System.Threading.Thread.Sleep(300);
                                string ip = cbx1.SelectedItem.ToString();
                                dicScoket[ip].Send(newBuffer);
                                tbx2.Text = "";
                                ShowMsg("我:" + str4);
                            }
                        }
                        catch { }
                    }
                    if (str1 == "02") 
                    {
                        string str2 = str.Substring(2);
                        string[] sArray = str2.Split('/');
                        string name = sArray[0];
                        int num = Convert.ToInt32(sArray[1]);
                        DataSet ds1 = Form1.conn.sql_search_database("select * from andr where name='" + name + "'");
                        int dsid = Convert.ToInt32(ds1.Tables[0].Rows[0][0]);
                        int dsnum = Convert.ToInt32(ds1.Tables[0].Rows[0][2]);
                        ShowMsg(socket.RemoteEndPoint.ToString() + ":" + str);
                        if (num > dsnum)
                        {
                            string a = "a";
                            this.send(a);

                        }
                        else
                        {
                            this.add(dsid, num);
                            this.update(dsnum - num, name);
                        }
                       
                    }

                }catch{}
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            conn.excute_sql("CREATE table abcd(nameID int identity(1,1) PRIMARY KEY,andr_id int,num int)");
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btSend_Click(object sender, EventArgs e)
        {
            try 
            {
                if(cbx1.SelectedItem==null)
                {
                    MessageBox.Show("请选中要发送的客户端哟");
                }
                for (int i = 0; i <ds.Tables[0].Rows.Count; i++)
                {
                    string str4 = ds.Tables[0].Rows[i][1].ToString();
                    string str5 = ds.Tables[0].Rows[i][2].ToString();
                    /*StringBuilder sb = new StringBuilder("");
                    sb.Append(str4);
                    sb.Append("/");
                    sb.Append(str5);*/
                    byte[] buffer = Encoding.UTF8.GetBytes(str4);
                    List<byte> list = new List<byte>();
                    list.Add(0);
                    list.AddRange(buffer);
                    byte[] newBuffer = list.ToArray();
                    System.Threading.Thread.Sleep(300); 
                    string ip = cbx1.SelectedItem.ToString();
                    dicScoket[ip].Send(newBuffer);
                    tbx2.Text = "";
                    ShowMsg("我:" + str4);
                }
            }
            catch { }
           
        }
        public void add(int nameid, int num)
        {
            Form1.conn.excute_sql("insert into abcd values('"+nameid+"','"+num+"')");
            
        }
        public void update(int num,string name)
        {
            Form1.conn.excute_sql("update andr set age='" + num + "' where name='" + name + "'");
        }
        public void send(string s)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(s);
            List<byte> list = new List<byte>();
            list.Add(0);
            list.AddRange(buffer);
            byte[] newBuffer = list.ToArray();
            System.Threading.Thread.Sleep(500);
            string ip = cbx1.SelectedItem.ToString();
            dicScoket[ip].Send(newBuffer);
            tbx2.Text = "";
            ShowMsg("我:" + s);
        }
    }
}
